<template>
  <div class="workorder-list-container">
    <el-loading v-if="isLoading" fullscreen />
    <div class="workorder-header">
      <el-button @click="goBack" type="default" icon="ArrowLeft">返回</el-button>
      <div class="workorder-list-title">我的维修工单</div>
      <el-button type="primary" @click="openWorkorderDialog">提交新工单</el-button>
    </div>
    <el-table :data="workorderList" style="width: 100%">

      <el-table-column prop="orderId" label="工单编号" width="100"></el-table-column>
      <el-table-column prop="description" label="故障原因"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column prop="status" label="工单状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button v-if="scope.row.status === 2" size="small" type="primary" @click="showEvaluateDialog(scope.row)">评价</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <SubmitWorkorder
    v-model:visible="showWorkorderDialog"
    @success="handleWorkorderSuccess"
  />

  <!-- 评价对话框 -->
  <el-dialog
    v-model="evaluateDialogVisible"
    title="评价工单"
    width="500px"
    :before-close="() => (evaluateDialogVisible = false)"
  >
    <div  class="evaluate-content">
      <div class="rating-section">
        <span class="label">评分:</span>
        <el-rate v-model="rating" :max="5" show-text></el-rate>
      </div>  
      <div class="feedback-section">
        <span class="label">评价内容:</span>
        <el-input
          v-model="feedback"
          type="textarea"
          placeholder="请输入您的评价..."
          :rows="4"
        ></el-input>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="evaluateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEvaluate">提交评价</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import service from '~/axios';
import { toast } from '~/composables/util';
import { getToken } from '~/composables/auth';
import { useAuthStore } from '~/stores/authStore';
import SubmitWorkorder from './submit-workorder.vue';

const showWorkorderDialog = ref(false);

const openWorkorderDialog = () => {
  showWorkorderDialog.value = true;
};

const handleWorkorderSuccess = () => {
  toast('工单提交成功');
  fetchWorkorders();
};

const router = useRouter();
const workorderList = ref([]);
const authStore = useAuthStore();
const isLoading = ref(true); // 添加加载状态

onMounted(() => {
  if (getToken()) {
    fetchWorkorders();
  } else {
    router.push('/login');
    ElMessage.warning('请先登录');
  }
});

const fetchWorkorders = async () => {
  isLoading.value = true;
  if (!getToken()) {
    toast('请先登录', 'warning');
    router.push('/login');
    isLoading.value = false;
    return;
  }
  try {
    const userId = authStore.userInfo?.id || 1;
    const url = `/api/user/GetAllOrderByUserId?user_id=${userId}`;
    const response = await service.get(url);
    workorderList.value = response.data.data || [];
    console.log('API响应数据:', workorderList.value);
  } catch (error) {
    toast('获取工单列表失败，请稍后重试', 'error');
  } finally {
    isLoading.value = false;
  }
};

const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '待处理';
    case 1:
      return '处理中';
    case 2:
      return '已完成';
    default:
      return '未知状态';
  }
};

const getStatusTagType = (status) => {
  switch (status) {
    case '待处理':
      return 'warning';
    case '处理中':
      return 'primary';
    case '已完成':
      return 'success';
    default:
      return 'default';
  }
};

const viewDetails = (row) => {
  router.push({ path: '/workorder-detail', query: { id: row.id } });
};

// 评价相关状态
const evaluateDialogVisible = ref(false);
const currentWorkorder = ref(null);
const rating = ref(5); // 默认5星
const feedback = ref('');

// 显示评价对话框
  const showEvaluateDialog = (row) => {
    currentWorkorder.value = row;
    rating.value = 5; // 重置评分
    feedback.value = ''; // 重置评价内容
    evaluateDialogVisible.value = true;
  };

// 提交评价
const submitEvaluate = async () => {
  if (!currentWorkorder.value) return;
  
  try {
    const userId = authStore.userInfo?.id || 1;
    console.log("fjkds"+currentWorkorder)
    const orderId = currentWorkorder.value.orderId;
    console.log("fjkdssfafdf"+orderId)
    
    // 使用组件中的rating和feedback值，而不是从currentWorkorder中获取
    const url = `/api/user/Comment?user_id=${encodeURIComponent(userId)}&Order_id=${encodeURIComponent(orderId)}&rating=${encodeURIComponent(rating.value)}&feedback=${encodeURIComponent(feedback.value)}`;

    const response = await service.post(url); 
    toast('评价提交成功');
    evaluateDialogVisible.value = false;
    fetchWorkorders(); // 刷新工单列表
  } catch (error) {
    toast('评价提交失败，请稍后重试', 'error');
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};
</script>

<style scoped>
.workorder-list-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.workorder-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.workorder-list-title {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.evaluate-content {
  padding: 10px 0;
}

.workorder-info {
  margin-bottom: 15px;
  color: #606266;
}

.rating-section,
.feedback-section {
  margin-bottom: 20px;
}

.label {
  display: inline-block;
  width: 60px;
  color: #606266;
}
</style>